package dat255.calendarclock.model.event;

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.LinkedList;
/**
 * This is the class used as access point to the Event and it's what occur on different days.
 * @author Marcus Hultman, Oskar Montin & Gabriel Andersson
 */
public class SubEvent implements Comparable<SubEvent> {

	//Fields
	private Event event;
	private GregorianCalendar date;
	
	// Private constructor, so that we know everything is fine.
	
	private SubEvent(Event event, GregorianCalendar date){
		this.event = event;
		this.date = date;
	}
	
	// Use these to create SubEvents.
	public static SubEvent create(Event event, GregorianCalendar targetTime){
		if (event != null){
			GregorianCalendar date = event.getInterval().nextDateOfEvent(targetTime);
			if (date != null){
				return new SubEvent(event, date);
			}
		}
		return null;
	}
	
	public static SubEvent create(Event event, GregorianCalendar targetTime,
			GregorianCalendar targetCap) {
		SubEvent subEvent = create(event, targetTime);
		if (subEvent != null && subEvent.getDate().before(targetCap)) {
			return subEvent;
		}
		return null;
	}
	
	// Get multiple SubEvents.
	/**
	 * 
	 * @param event
	 * @param targetTime
	 * @param targetCap
	 * @return All events from the targetTime until the targetCap.
	 */
	public static LinkedList<SubEvent> getEvents(Event event, GregorianCalendar targetTime, 
			GregorianCalendar targetCap){
		LinkedList<SubEvent> listOfEvents = new LinkedList<SubEvent>();
		GregorianCalendar comparingDate = targetTime;
		while (true){
			SubEvent sub = create(event, comparingDate, targetCap);
			if (sub != null)
				listOfEvents.add(sub);
			else 
				return listOfEvents;
			comparingDate = sub.getDate();
		}
	}
	
	// Public methods
	public boolean hasHappened(){
		return date.before(new GregorianCalendar());
	}
	
	public GregorianCalendar getDate(){
		return this.date;
	}
	
	public Event getEvent(){
		return this.event;
	}
	
	public String getFormatedDateString() {
		return new SimpleDateFormat("kk':'mm' - 'EEE' 'dd'/'MM' 'yyyy").
				format(this.getDate().getTime());
	}
	
	/**
	 * @returns -1 when this is before another, 1 when after. 
	 * 	Otherwise returns the compareTo of Name.
	 */
	public int compareTo(final SubEvent another) {
		if(this.date.after(another.date))
			return 1;
		if(this.date.before(another.date))
			return -1;
		return this.event.getName().compareTo(another.event.getName());
	}
	
	@Override
	public String toString(){
		return this.event.getName();
	}
	
}
